upcamera.Upcamera = zk.$extends(zul.Widget, {

    _maxCount: null,
    _type: null,
    _imgJson: {},
    _fileCount: 0,
    _resultOld: null,

    $define: {
        maxCount: function (val) {
        },
        type: function (val) {
        },
    },

    unbind_: function () {
        this.$supers(upcamera.Upcamera, 'unbind_', arguments);
        this._imgJson = {};
    },


    doClick_: function (evt) {
    },

    bind_: function () {
        this.$supers(upcamera.Upcamera, 'bind_', arguments);
        this._imgJson = {};

        if(this._type != 'invoke') {
            const dragCon = document.getElementById(this.uuid+'-imgList');
            dragCon.addEventListener('dragstart', startDrag, false);
            dragCon.addEventListener('dragover', function (e) {
                e.preventDefault();
            }, false);
            dragCon.addEventListener('drop', exchangeElement, false);

            function startDrag(e) {
                e.dataTransfer.setData('Text', e.target.id + ';' + e.target.parentElement.id);
            }

            function exchangeElement(e) {
                e.preventDefault();
                const el = e.target;
                var PE; //要插入位置的父元素
                var CE; //需要交换的元素
                if (el.tagName.toLowerCase() !== 'li') {
                    PE = el.parentElement;
                    CE = el;
                } else {
                    PE = el;
                    CE = el.querySelector('img');
                }
                console.log(PE.classList)
                if (!PE.classList.contains('el-upload-list__item')) {
                    return;
                }
                const data = e.dataTransfer.getData('Text').split(';');
                //交换元素\n' +
                document.getElementById(data[1]).appendChild(CE);
                PE.appendChild(document.getElementById(data[0]));
            }
        }
    },

    takePictures: function (e) {
        var that = this;
        var Orientation;
        var filePath = e.target.files[0].name;
        var fileFormat = filePath.substring(filePath.lastIndexOf('.')).toLowerCase();
        var fileObj = e.target.files[0];
        if (!fileFormat.match(/.png|.jpg|.jpeg|.gif/)) {
            alert('文件类型错误,文件格式必须为:png/jpg/jpeg!');
            return;
        }
        if(this._resultOld === fileObj){
            alert('请上传不同的图片');
            return;
        }
        this._resultOld = fileObj;

        /*获取图片方向信息*/
        EXIF.getData(fileObj, function () {
            Orientation = EXIF.getTag(this, 'Orientation') || '';
        });

        if (typeof (FileReader) === 'undefined') {
            alert("抱歉，你的浏览器不支持 FileReader，图片处理失败");
            return;
        } else {
            try {
                var reader = new FileReader();
                var image = new Image();
                reader.onload = function (e) {
                    image.setAttribute('src', e.target.result);
                };
                reader.readAsDataURL(fileObj);
                image.onload = function () {
                    if (fileObj.size < 300 * 1024) {
                        // 调用处理函数 小于300kb直接上传
                        if (Orientation === 3 || Orientation === 6 || Orientation === 8) {
                            /*调用旋转函数*/
                            that.rotateImg(this, Orientation, function (rotateData) {
                                that.addImgUl(rotateData);
                            });
                        } else if (Orientation === '' || Orientation === 1) {
                            /*不进行旋转*/
                            that.addImgUl(this.src);
                        }
                        return;
                    } else {
                        //超过300kb 加载完后压缩
                        var data = that.compress(this);
                        if (Orientation === 3 || Orientation === 6 || Orientation === 8) {
                            /*调用旋转函数*/
                            that.rotateImg(data, Orientation, function (rotateData) {
                                that.addImgUl(rotateData);
                            });
                        } else if (Orientation === '' || Orientation === 1) {
                            /*不进行旋转*/
                            that.addImgUl(data);
                        }
                        return;
                    }
                }
            } catch (e) {
                alert('图片处理失败：'+e);
                return;
            }
        }
    },

    compress: function (image) {
        //用于压缩图片的canvas
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext('2d');
        //瓦片canvas
        var tCanvas = document.createElement("canvas");
        var tctx = tCanvas.getContext("2d");

        var initSize = image.src.length;
        var width = image.width;
        var height = image.height;
        //如果图片大于四百万像素，计算压缩比并将大小压至300万以下,图片仍过大可继续减小像素
        var ratio;
        if ((ratio = width * height / 3000000) > 1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        } else {
            ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
        //铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于150万则使用瓦片绘制，图片仍过大可继续减小像素
        var count;
        if ((count = width * height / 1500000) > 1) {
            count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
            //计算每块瓦片的宽和高
            var nw = ~~(width / count);
            var nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;
            for (var i = 0; i < count; i++) {
                for (var j = 0; j < count; j++) {
                    tctx.drawImage(image, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                }
            }
        } else {
            ctx.drawImage(image, 0, 0, width, height);
        }

        //进行最小压缩
        var data = canvas.toDataURL('image/jpeg', 0.1);
        //console.log('压缩前：' + initSize);
        //console.log('压缩后：' + data.length);
        //console.log('压缩率：' + ~~(100 * (initSize - data.length) / initSize) + "%");
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        return data;
    },

    rotateImg: function (img, dir, callback) {
        var image = new Image();
        image.onload = function () {
            var degree = 0, drawWidth, drawHeight, width, height;
            drawWidth = this.naturalWidth;
            drawHeight = this.naturalHeight;
            //以下改变一下图片大小
            var maxSide = Math.max(drawWidth, drawHeight);
            if (maxSide > 1024) {
                var minSide = Math.min(drawWidth, drawHeight);
                minSide = minSide / maxSide * 1024;
                maxSide = 1024;
                if (drawWidth > drawHeight) {
                    drawWidth = maxSide;
                    drawHeight = minSide;
                } else {
                    drawWidth = minSide;
                    drawHeight = maxSide;
                }
            }
            var canvas = document.createElement('canvas');
            canvas.width = width = drawWidth;
            canvas.height = height = drawHeight;
            var context = canvas.getContext('2d');
            //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
            switch (dir) {
                //iphone横屏拍摄，此时home键在左侧
                case 3:
                    degree = 180;
                    drawWidth = -width;
                    drawHeight = -height;
                    break;
                //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
                case 6:
                    canvas.width = height;
                    canvas.height = width;
                    degree = 90;
                    drawWidth = width;
                    drawHeight = -height;
                    break;
                //iphone竖屏拍摄，此时home键在上方
                case 8:
                    canvas.width = height;
                    canvas.height = width;
                    degree = 270;
                    drawWidth = -width;
                    drawHeight = height;
                    break;
            }
            //使用canvas旋转校正
            context.rotate(degree * Math.PI / 180);
            context.drawImage(this, 0, 0, drawWidth, drawHeight);
            //返回校正图片
            callback(canvas.toDataURL("image/jpeg", .8));
        }
        image.src = img;
    },

    addImgUl: function (imgBase64) {
        if (this._type == 'invoke') {
            this._imgJson['temp'] = imgBase64;
            this.doSave(imgBase64);
        } else {
            this.saveImg(this.uuid+"-imgLi" + this._fileCount, imgBase64);
            $('#'+this.uuid+'-imgList').append(
                '<li class="el-upload-list--picture-card el-upload-list__item" id='+this.uuid+'-imgLi' + this._fileCount + ' onclick=zk.$("' + this.uuid + '").showImg("' + imgBase64 + '","' + this.uuid + '-imgLi' + this._fileCount + '")>\n' +
                '    <div id=' + this.uuid + '-img' + this._fileCount + ' style="width:100%;height:100%;background-image:url(&apos;' + imgBase64 + '&apos;);background-size: cover;background-repeat:no-repeat;" draggable="true" >\n' +
                '</li>');
            this._fileCount = $("#"+this.uuid+"-imgList").children().length;
            if (this._fileCount < this._maxCount) {
                $('#'+this.uuid+'-uploadInput').attr("style", "display:inline-block;");
            } else {
                $('#'+this.uuid+'-uploadInput').attr("style", "display:none;");
            }
        }
    },


    showImg: function (imgBase64, imgId) {
        $('#'+this.uuid+'-showDiv').attr("style", "display:block;");
        $('#'+this.uuid+'-showImg').attr("src", imgBase64);
        $('#'+this.uuid+'-showImg').attr("title", imgId);
    },

    exitImg: function () {
        $('#'+this.uuid+'-showDiv').attr("style", "display:none;");
    },

    deleteImg: function (imgLiId) {
        delete this._imgJson[imgLiId];
        this.doSave(this._imgJson);
        $('#'+this.uuid+'-showDiv').attr("style", "display:none;");
        $("#" + imgLiId).remove();
        this._fileCount = $("#"+this.uuid+"-imgList").children().length;
        if (this._fileCount < this._maxCount) {
            $('#'+this.uuid+'-uploadInput').attr("style", "display:inline-block;");
        }
    },

    saveImg: function (imgLiId, imgBase64) {
        this._imgJson[imgLiId] = imgBase64;
        this.doSave(this._imgJson);
    },

    getAllImg: function () {
        var imgJson = {};
        for (var i = 0; i < $("ul div").length; i++) {
            var imgName = "图片" + i;
            var imgBase64 = $("ul div")[0].style.backgroundImage.replace('url("', '').replace('")', '');
            imgJson[imgName] = imgBase64;
        }
        this.doSave(imgJson);
    },

    execute: function () {//外部调用方法
        if (this._type == 'invoke') {
            $("#"+this.uuid+"-input").click();
        }
    },

    show: function (evt) {//刷新外部img标签
        if (this._type == 'invoke') {
            var image = document.getElementById(evt);
            image.setAttribute('style', 'background-size: cover;' +
                'background-repeat:no-repeat;' +
                'background-image:url("' + this._imgJson['temp'] + '");');
        }
    },


    doSave: function (evt) {
        this.fire("onSave",{data:evt});
        this.fire("onClick", {data: evt});
    },

});